class League < ActiveRecord::Base
  belongs_to :country
  belongs_to :sport
  
  validates_presence_of :sport_id


  def find_or_create_team(team_name,league)
    team = Team.find_or_initialize_by_name(team_name)
    team.sport  = league.sport
    team.save!
    team
  end

  def fetch_results
    urls = [
      "http://www.scorespro.com/rss/live-soccer.xml",
      "http://www.scorespro.com/rss/live-basketball.xml"
    ]
    next_match = Match.next_match
    matches = [] 
    urls.each do |url|
      content = open(url) do |file|
        file.read
      end
      data = Hash.from_xml(content)
      data["rss"]["channel"]["item"].each do |item|
        title = item["title"]
        regexp = /^\s*(.+?)\s*\-\s*(.+?)\s*(\d{1,3})\s*\-\s*(\d{1,3}).+?$/
        if title =~ regexp
          home_team_name,away_team_name,home_point,away_point =  $1,$2,$3,$4
          home_team = Team.find_by_name_alias(home_team_name)
          away_team = Team.find_by_name_alias(away_team_name)
          if home_team && away_team
            # if match exists , then process it
            match = Match.find_by_home_team_id_and_away_team_id(home_team.id,away_team.id)
            if match
              # match.play_from_point(home_point,away_point)
              if next_match == match
                # we found the next match
                next_match.play_from_point(home_point,away_point)
                next_match = Match.next_match
              end
              matches << match
            end
          end
        end
      end
    end
    matches
  end

  # deprecated 
  def update_matches_from_feed
    hash = self.class.hash_from_feed feed_url
    odds = hash["odds"]
    entries = odds["entry"]
    success_count = 0
    unless entries.blank?
      entries.each do |entry|
        away_team_name = entry["awayteam"]
        home_team_name = entry["hometeam"]
        home_line = away_line = nil
        away_line = self.class.parse_line(entry["awayline"])
        away_line = self.class.parse_line(entry["awayline"])

        away_team = find_or_create_team(away_team_name)
        home_team = find_or_create_team(home_team_name)

        begin_at = self.class.parse_date_time(entry["date_time"])
        match = Match.find_or_initialize_by_home_team_id_and_away_team_id_and_begin_at(
          home_team.id,
          away_team.id,
          begin_at
        )

        match.point_spread = home_line
        success_count += 1 if match.save
      end
    end
    success_count
  end

  # return an hash from given xml url
  def self.hash_from_feed(url)
    open(url){ |f| Hash.from_xml(f.read) }
  end

  def self.parse_line(line)
    $1.to_f if line =~ /^(\-?[\d\.]+?)\((\-?[\d\.]+?)\)$/
  end

  # original: 12-09-08 9:10 PM
  # fixed:    2008-12-09 9:10 PM
  def self.parse_date_time(str)
    str = str.gsub(/^(\d{1,2})\-(\d{1,2})\-(\d{1,2})(.+)$/,"20\\3-\\1-\\2\\4")
    DateTime.parse str
  end

  def self.from_hash(hash,sport)
    name = hash["league"]
    country = Country.find_by_name(hash["country"])
    returning League.find_or_initialize_by_name_and_country_id(name,country.id) do |league|
      league.sport = sport
      league.save
    end
  end

end
